package com.pig4cloud.pigx.contract.executer.position.multiple_changer.impl;

import com.alibaba.nacos.common.utils.Objects;
import com.pig4cloud.pigx.common.customize.i18n.util.MessageUtils;
import com.pig4cloud.pigx.common.customize.mysql.utils.MysqlUtil;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.contract.bo.ContractPositionMultipleChangeBO;
import com.pig4cloud.pigx.contract.constant.I18nMessages;
import com.pig4cloud.pigx.contract.dto.AppContractMultipleChangeDTO;
import com.pig4cloud.pigx.contract.entity.ContractPosition;
import com.pig4cloud.pigx.contract.enums.ContractPositionEnum;
import com.pig4cloud.pigx.contract.executer.position.multiple_changer.PositionMultipleChangerManager;
import com.pig4cloud.pigx.contract.mapper.ContractPositionMapper;
import com.pig4cloud.pigx.contract.utils.ContractUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 逐仓仓位杠杆调整器
 *
 * @since 2022/8/17 21:26
 */
@Component
public class IsolatedPositionMultipleChanger extends AbstractPositionMultipleChanger
		implements InitializingBean {

	protected final PositionMultipleChangerManager positionMultipleChangerManager;

	/**
	 * 全参构造函数
	 *
	 * @since 2022/9/8 14:45
	 */
	public IsolatedPositionMultipleChanger(ContractUtils contractUtils,
										   CommonUtil commonUtil,
										   MysqlUtil mysqlUtil,
										   ContractPositionMapper contractPositionMapper,
										   PositionMultipleChangerManager positionMultipleChangerManager) {
		super(contractUtils, commonUtil, mysqlUtil, contractPositionMapper);
		this.positionMultipleChangerManager = positionMultipleChangerManager;
	}

	/**
	 * 当前对象创建后
	 *
	 * @since 2022/9/8 11:08
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		positionMultipleChangerManager.getMultipleHandlerList().add(this);
	}

	/**
	 * 判断是否支持
	 *
	 * @param bo bo
	 * @return {@link boolean}
	 * @since 2022/8/17 11:20
	 */
	@Override
	public boolean support(ContractPositionMultipleChangeBO bo) {
		// 同一币对下仓位模式相同
		ContractPosition position = bo.getFirstPosition();
		return Objects.equals(ContractPositionEnum.Mode.ISOLATED.getValue(), position.getMode());
	}

	/**
	 * 校验调整参数
	 *
	 * @param bo bo
	 * @since 2022/9/8 11:23
	 */
	@Override
	protected void validChangeParam(ContractPositionMultipleChangeBO bo) {
		super.validChangeParam(bo);

		AppContractMultipleChangeDTO dto = bo.getDto();
		ContractPosition position = bo.getFirstPosition();
		// 逐仓只能往更高处调整
		if (position.getMultiple() > dto.getMultiple()) {
			throw new RuntimeException(MessageUtils.get(I18nMessages.UNABLE_TO_REDUCE_LEVERAGE_MULTIPLES));
		}
	}

	/**
	 * 处理因杠杆倍数变化导致更改的其它相关数据
	 *
	 * @param bo bo
	 * @since 2022/9/8 12:04
	 */
	@Override
	protected void handleRelevantData(ContractPositionMultipleChangeBO bo) {
	}
}
